<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\View;
use App\Services\Database;
use App\Core\CSRF;
use App\Services\Auth;
use PDO;

final class PostController
{
    public function index(): string
    {
        $pdo = Database::pdo();

        $kw = trim((string)($_GET['kw'] ?? ''));
        $page = (int)($_GET['page'] ?? 1);
        if ($page < 1) {
            $page = 1;
        }
        $perPage = 10;
        $offset = ($page - 1) * $perPage;

        $where = '';
        $params = [];
        if ($kw !== '') {
            $where = 'WHERE title LIKE :kw1 OR content LIKE :kw2';
            $params[':kw1'] = '%' . $kw . '%';
            $params[':kw2'] = '%' . $kw . '%';
        }

        // 统计总数
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM posts {$where}");
        foreach ($params as $k => $v) {
            $stmt->bindValue($k, $v, PDO::PARAM_STR);
        }
        $stmt->execute();
        $total = (int) $stmt->fetchColumn();

        // 查询列表（注意：MySQL 在非模拟预处理下不支持为 LIMIT/OFFSET 绑定参数）
        $sql = "SELECT id, title, content, created_at, updated_at FROM posts {$where} ORDER BY created_at DESC LIMIT {$perPage} OFFSET {$offset}";
        $stmt = $pdo->prepare($sql);
        foreach ($params as $k => $v) {
            $stmt->bindValue($k, $v, PDO::PARAM_STR);
        }
        $stmt->execute();
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

        $totalPages = max(1, (int) ceil($total / $perPage));

        return View::render('posts/index', [
            'title' => '文章列表',
            'posts' => $rows,
            'kw' => $kw,
            'page' => $page,
            'totalPages' => $totalPages,
            'pagination' => [
                'page' => $page,
                'perPage' => $perPage,
                'total' => $total,
                'totalPages' => $totalPages,
            ],
        ]);
    }

    public function show(string $id): string
    {
        $post = $this->find((int)$id);
        if (!$post) {
            http_response_code(404);
            return 'Post not found';
        }
        // 详情页模板简版展示
        $html  = "<h1>" . htmlspecialchars($post['title'] ?? '', ENT_QUOTES, 'UTF-8') . "</h1>";
        $html .= "<div><a href=\"/posts\">返回列表</a></div><hr>";
        $html .= "<div>" . nl2br(htmlspecialchars($post['content'] ?? '', ENT_QUOTES, 'UTF-8')) . "</div>";
        return $html;
    }

    public function create(): string
    {
        if (!$this->requireLogin()) {
            return '';
        }
        return View::render('posts/form', [
            'title' => '新建文章',
            'action' => '/posts/create',
            'post' => ['title' => '', 'content' => ''],
        ]);
    }

    public function store(): string
    {
        if (!$this->requireLogin()) {
            return '';
        }
        CSRF::validateOrAbort();
        $title = trim((string)($_POST['title'] ?? ''));
        $content = trim((string)($_POST['content'] ?? ''));
        if ($title === '' || $content === '') {
            http_response_code(400);
            return '标题与内容均为必填';
        }
        $pdo = Database::pdo();
        $stmt = $pdo->prepare("INSERT INTO posts (title, content) VALUES (:title, :content)");
        $stmt->execute([':title' => $title, ':content' => $content]);
        header('Location: /posts');
        return '';
    }

    public function edit(string $id): string
    {
        if (!$this->requireLogin()) {
            return '';
        }
        $post = $this->find((int)$id);
        if (!$post) {
            http_response_code(404);
            return 'Post not found';
        }
        return View::render('posts/form', [
            'title' => '编辑文章',
            'action' => '/posts/' . (int)$id . '/edit',
            'post' => $post,
        ]);
    }

    public function update(string $id): string
    {
        if (!$this->requireLogin()) {
            return '';
        }
        CSRF::validateOrAbort();
        $title = trim((string)($_POST['title'] ?? ''));
        $content = trim((string)($_POST['content'] ?? ''));
        if ($title === '' || $content === '') {
            http_response_code(400);
            return '标题与内容均为必填';
        }
        $pdo = Database::pdo();
        $stmt = $pdo->prepare("UPDATE posts SET title = :title, content = :content WHERE id = :id");
        $stmt->execute([':title' => $title, ':content' => $content, ':id' => (int)$id]);
        header('Location: /posts');
        return '';
    }

    public function destroy(string $id): string
    {
        if (!$this->requireLogin()) {
            return '';
        }
        CSRF::validateOrAbort();
        $pdo = Database::pdo();
        $stmt = $pdo->prepare("DELETE FROM posts WHERE id = :id");
        $stmt->execute([':id' => (int)$id]);
        header('Location: /posts');
        return '';
    }

    private function find(int $id): ?array
    {
        $pdo = Database::pdo();
        $stmt = $pdo->prepare("SELECT id, title, content, created_at, updated_at FROM posts WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row ?: null;
    }

    private function requireLogin(): bool
    {
        if (!Auth::check()) {
            header('Location: /login');
            return false;
        }
        return true;
    }
}
